<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @abstract 递4方请求接口 4px
 * @author zxj
 */
class RepairOrder extends CI_Controller
{
    private $getData; //得到数据

    function __construct()
    {
        parent::__construct();
        $this->getData = gp();
        if ($this->getData) {
            log_output($this->getData); //将数据写入日志
        }
        //第四方登录验证
        $this->userSigna($this->getData['user'], $this->getData['key']);
        //加载模型
        $this->load->model('order_model');
        $this->load->model('product_model');
    }


    /**
     * 验证是否登录
     * @param string $user 用户名
     * @param string $key 密码
     * @return mixed
     */
    function userSigna($user = '', $key = '')
    {
        //输出数据结构
        $where = array('account' => $user, 'password' => md5($key));
        if (!$user or !$key) {
            json_output('', 'User not exist.', false);
        } else {
            $userFirst = $this->common_model->selectFirst('user', $where);
            if (!$userFirst) {
                json_output(array('userFirst' => $userFirst, 'key' => $key, 'user' => $user), '帐号密码错误.', false);
            }
        }
        return true;
    }


    /**
     * es  david  order
     */
    public function addOrder(){
        $orders = json_decode($this->getData['orders'],true);
        if (!$orders) {
            json_output('', 'Create order data can not be empty!', false);
        }
        if (!$orders['products_list'] || !is_array($orders['products_list'])) {
            json_output('', 'Create product data can not be empty!', false);
        }
        //创建订单
        $repair_point = strtolower($orders['repair_point']); //维修站点
        if (!$repair_point) {
            json_output('', 'field repair_point NOT NULL', false);
        }
        $repairSite = $this->order_model->selectFirst('mt_repair_site', array('site_prefix' => $repair_point));
        $orderData['repair_site_id'] = $repairSite['id']; //维修站点
        $orderData['source_site_id'] = $orders['source_site_id'];  //12=www.flowrepair.es
        $oid = $this->order_model->createRepairId($orderData['repair_site_id']);
        if (!$oid) {
            json_output('', 'Generate maintenance number failed,error:'.$repair_point, false);
        }
        $orderData['maintain_id'] = $oid;
        $orderData['status_id'] = 1; //订单状态,默认是1
        $orderData['maintain_type_id'] = $orders['repair_type']; //维修类型
        $orderData['source_int_id'] = $orders['reference_order_number']; //来源单号  source_order

        /*
        //website_origin
        $data['originList'] = array(
            '1'=>'pandaClever','2'=>'valukect','3'=>'rakuten','4'=>'pandawill',
            '5'=>'elephone','6'=>'aliexpress','7'=>'carrefour','8'=>'zopo',
            '9'=>'morefine','10'=>'freefeet','11'=>'geekvida_es','12'=>'geekvida_pt'
        );
        */

        $orderData['website_origin'] = $orders['website_origin']; //来源网站
        $orderData['account_origin'] = $orders['account_origin']; //来源帐号
        $orderData['source_id'] = $orders['source_id_order']; //Third party order_id 第三方单号

        /*
        $orderFirst = $this->common_model->selectFirst('maintain_order',array('source_id'=>$orders['source_ae_order']));
        if($orderFirst){
            json_output(array('oid'=>$orderFirst['maintain_id']), 'Return current order', true);
        }
        */

        $orderData['consumer_name'] = $orders['customer_name']; //客户名称
        $orderData['consumer_phone'] = $orders['customer_phone']; //客户电话
        $orderData['consumer_email'] = $orders['customer_email']; //客户邮箱

        //收件地址一般和送件地址相同，修好再寄回去
        if(is_numeric($orders['pickup_service'])){
            $orderData['pickup_service'] = $orders['pickup_service']; //收件方式 0否 1是
        }
        $orderData['pickup_address'] = $orders['pickup_address']; //收件地址
        if(is_numeric($orders['delivery_service'])){
            $orderData['delivery_service'] = $orders['delivery_service']; //送件方式 0否 1是
        }
        $orderData['delivery_address'] = $orders['delivery_address']; //送件地址
        //----待删除
        $orderData['consumer_address'] = $orders['delivery_address']; //客户地址
        $orderData['delivery_country'] = $orders['delivery_country'];
        $orderData['delivery_city'] = $orders['delivery_city'];
        $orderData['delivery_state'] = $orders['delivery_state'];
        $orderData['delivery_street_address'] = $orders['delivery_street_address'];
        $orderData['delivery_zipcode'] = $orders['delivery_zipcode'];

        $orderData['add_user'] = $this->getData['user']; //添加人
        $orderData['add_time'] = date('Y-m-d H:i:s'); //添加时间
        $this->order_model->addOrSetOrder($orderData);

        //添加产品
        $products = $orders['products_list'];
        $productData['maintain_id'] = $oid;

        $productData['sort_id'] = $products['products_sort']?$products['products_sort']:1;

        $productData['brand_id'] = $products['products_brand_id'];
        $productData['product_model'] = $products['products_model'];
        $productData['source_product_id'] = $products['products_id'];
        $productData['brand_name'] = $products['products_brand_name'];
        $productData['imei'] = $products['imei'];
        //http://flowrepair.es/new/media/tickets/PHOTO_FILE_NAME
        $productData['photos'] = serialize($products['photos']);
        $productData['video'] = $products['video'];
        $productData['size'] = $products['size'];
        $productData['color'] = $products['color'];
        $productData['is_bluetooth'] = $products['is_bluetooth'];
        $productData['is_yaokong'] = $products['is_remote_control'];
        $productData['remark_customer'] = $products['remark_customer'];
        $this->product_model->addOrSetProduct($productData);
        json_output(array('oid'=>$oid), 'Create order success', true);
    }


    /**
     * 创建订单新接口
     */
    function create_order_new()
    {
        $orders = json_decode($this->getData['orders'] , true);
        //begin
        //新增批量单验证，应tomrepair需求，他们调用的是同一个接口，多一个batch_operations字段判断是否为批量单
        //sqingwen 2016/1226
        if ($orders['batch_operations'] == 1) {
            $this->CreateMultiOrder($orders);
            exit;
        }
        //end
        $products = $orders['products_list'];
        if (!$orders) {
            json_output('', 'Create order data can not be empty!', false);
        }
        if (!$products || !is_array($products)) {
            json_output('', 'Create product data can not be empty!', false);
        }
        $point = strtolower($orders['repair_point']);
        $serviceCenter = $this->common_model->selectFirst('mt_service_center', array('point' => $point));
        if (!$point) {
            json_output('', '(repair site)service Center not exist', false);
        }
        $orderNum = build_order_no();
        $orderData['order_num'] = $orderNum;
        $orderData['website_origin'] = $orders['website_origin'];
        $orderData['service_center'] = $serviceCenter['id'];
        $orderData['point'] = $serviceCenter['point'];
        $orderData['currency_code'] = $serviceCenter['currency'];
        $sourceSiteAry = array('ES' => 2, 'RU' => 3, 'DE' => 4, 'GB' => 6, 'US' => 7, 'SZ' => 5);
        $sitePoint = strtoupper($point);
        $orderData['source_site'] = $sourceSiteAry[$sitePoint]; //订单来源
        $orderData['consumer_type'] = 'repair'; //客户类型
        $orderData['service_type'] = $orders['repair_type'];
        $orderData['product_quantity'] = $orders['quantity'] ?: count($products);
        //返修单号
        if ($orders['repair_type'] == 4) {
            if (!$orders['rework_orderNum']) {
                json_output($orders, 'filed rework_orderNum not Null', false);
            }
            $orderData['rework_orderNum'] = $orders['rework_orderNum'];
        }
        $orderData['consumer_name'] = $orders['customer_name'];
        $orderData['consumer_phone'] = $orders['customer_phone'];
        $orderData['consumer_email'] = $orders['customer_email'];
        $orderData['storeOrShip'] = $orders['storeOrShip'];
        $orderData['consumer_address'] = $orders['consumer_address'];
        if (!$orders['consumer_address']) {
            $orderData['consumer_address'] = $orders['delivery_address'];
        }
        $orderData['pickup_service'] = 1;
        if(is_numeric($orders['pickup_service'])){
            $orderData['pickup_service'] = $orders['pickup_service'];
        }
        $orderData['pickup_address'] = $orders['pickup_address'];
        $orderData['delivery_service'] = $orders['delivery_service'];
        $orderData['delivery_address'] = $orders['delivery_address'];

        $orderData['delivery_country'] = $orders['delivery_country'];
        $orderData['delivery_city'] = $orders['delivery_city'];
        $orderData['delivery_state'] = $orders['delivery_state'];
        $orderData['delivery_street_address'] = $orders['delivery_street_address'];
        $orderData['delivery_zipcode'] = $orders['delivery_zipcode'];

        $orderData['nif'] = $orders['nif'];
        $orderData['aws'] = $orders['aws'];
        $orderData['remark'] = $orders['remark'];


        //#卖家
        $merchantNum = (int)$orders['merchant_num'];
        if ($orders['merchant_num'] && $merchantNum != 35) {
            $merchantFirst = $this->common_model->selectFirst('mt_customers', array('id' => $merchantNum));
            if ($merchantFirst['type'] != 1) {
                json_output($merchantFirst, 'No platform customers', false);
            }
        }
        $orderData['merchant_num'] = $merchantNum;
		$orderData['napa_stores_num'] = $orders['napa_stores_num'];
        //#个人
        $consumerNum = 0;
        if (!$orderData['merchant_num'] && $orderData['consumer_email']) {
            $consumerFirst = $this->common_model->selectFirst('mt_customers', array('email' => $orderData['consumer_email']));
            if ($consumerFirst['type'] == 3) {
                $consumerNum = $consumerFirst['id'];
            } else {
                $consumerData = array(
                    'name' => $orderData['consumer_name'], 'email' => $orderData['consumer_email'],
                    'tel' => $orderData['consumer_phone'], 'type' => 3, 'CurrencyIsoCode' => $serviceCenter['currency_code']
                );
                $consumerNum = $this->common_model->insert('mt_customers', $consumerData);
            }
        }
        $orderData['consumer_num'] = $consumerNum;

        $orderData['create_time'] = $orders['create_time'];
        $orderData['add_time'] = strtotime($orders['create_time']);
        $orderData['add_user'] = $this->getData['user'];
        $orderData['source_oid'] = $orders['reference_order_number'] ? $orders['reference_order_number'] : uniqid('OM');
        if($orders['reference_order_number']){
            $referenceOrder = $this->common_model->selectFirst('mt_order',array('source_oid'=>$orders['reference_order_number']));
            if($referenceOrder){
                json_output($orderData, 'reference order:'.$orders['reference_order_number'].' already existed', false);
            }
        }
        //验证产品类型是否存在
        foreach ($products as &$rs) {
            $productTypes = $this->common_model->selectFirst('mt_product_category',array('sap_id'=>$rs['category']));
            if(!$productTypes){
                json_output($orderData, 'productType id:'.$rs['category'].' is not exist', false);
            }
            $rs['category'] = $productTypes['id'];
        }
        unset($rs);
        //插入订单
        $oid = $this->common_model->insert('mt_order', $orderData);
        if (!$oid) {
            json_output($orderData, 'Failed to create the order', false);
        }
        //循环插入产品
        $pids = array();
        foreach ($products as $rs) {
            //add product
            $productData = array();
            $productData['oid'] = $oid;
            $productData['order_num'] = $orderNum;
            $productData['category_id'] = $rs['category'];
            //产品数量
            $quantity = $rs['product_quantity'] ? $rs['product_quantity'] : 1;
            for ($i = 0; $i < $quantity; $i++) {
                $productData['productSku'] = $rs['productSku'];
                $productData['fpx_sku'] = $rs['fpx_sku'];
                $productData['attributes'] = $rs['attributes'];
                $productData['source_id_order'] = $rs['source_id_order'];
                $productData['product_brand'] = $rs['product_brand'];
                $productData['product_model'] = $rs['product_model'];
                $productData['model_id'] = $rs['model_id'];
                $productData['customerRemark'] = $rs['remark_customer'];
                $productData['defectDes'] = $rs['defectDes'];
                $productData['imei'] = $rs['imei'];
                $productData['brandCustomerNum'] = (int)$rs['brandCustomerNum'];
                if (is_numeric($rs['inWarranty_tr'])) {
                    $productData['inWarranty_tr'] = $rs['inWarranty_tr'];
                }
                if (is_numeric($rs['seller_warranty'])) {
                    if($rs['seller_warranty']==='0'){
                        $productData['inWarranty_qc'] = 0;
                        $productData['inWarranty'] = 0;
                    }
                    $productData['seller_warranty'] = $rs['seller_warranty'];
                }
                $productData['photos1'] = $rs['photo1'];
                $productData['photos2'] = $rs['photo2'];
                $productData['photos3'] = $rs['photo3'];
                $productData['photos4'] = $rs['photo4'];
                $productData['photos5'] = $rs['photo5'];
                $productData['photos6'] = $rs['photo6'];
                $productData['videoUrl'] = $rs['video'];
                $productData['create_time'] = $orders['create_time'];
                $productData['add_time'] = time();
                $productData['add_user'] = 'system';
                //标记产品为返修
                if ($orders['repair_type'] == 4) {
                    if($quantity==1 && substr($orderData['source_oid'],0,2) != 'OM'){
                        $this->common_model->update('mt_product', array('isRework' => 1), array('order_num' => $orders['rework_orderNum']));
                    }else{
                        $productData['rework_pid'] = $rs['rework_pid'];
                        $this->common_model->update('mt_product', array('isRework' => 1), array('id' => $rs['rework_pid']));
                    }
                }
                $pid = $this->common_model->insert('mt_product', $productData);
                $pids[] = $pid;
                //推送环球易购信息
                if($orderData['merchant_num']==428) {
                    $this->load->library('GlobalEGrow');
                    $globalEGrow = new GlobalEGrow();
                    $data=$globalEGrow->transferRepairInfo($pid);
                    if($data['code']==0){
                        $address=$globalEGrow->transferAddress($pid);
                        if($address['code']==0) {
                            $jsonData['is_sync'][] = $pid;
                        }else{
                            json_output(array('source_oid'=>$orderData['source_oid']), 'sync Address error:'.$data['msg'], false);
                        }
                    }else{
                        json_output(array('source_oid'=>$orderData['source_oid']), 'sync RepairInfo error:'.$data['msg'], false);
                    }
                }
            }
        }
        json_output(array('oid' => $orderNum, 'orderid' => $oid, 'pids' => $pids,'customer_name'=>$orders['customer_name']), 'Create order successfully', true);
    }



    /**
     * 创建订单
     */
    function create_order()
    {
        //接受订单数据
        $orders = json_decode($this->getData['order'], true);
        if (!$orders) {
            json_output('', '未接收到订单数据', false);
        }
        if (!$orders['products_list'] || !is_array($orders['products_list'])) {
            json_output('', '未接收到产品数据', false);
        }
        //创建订单
        $repair_point = strtolower($orders['repair_point']); //维修站点
        if (!$repair_point) {
            json_output('', '维修站点不能为空', false);
        }
        if($repair_point == 'gb')$repair_point = 'uk';
        $repairSite = $this->order_model->selectFirst('mt_repair_site', array('site_prefix' => $repair_point));
        $orderData['repair_site_id'] = $repairSite['id']; //维修站点
        $orderData['source_site_id'] = 8;  //来源站点
        $oid = $this->order_model->createRepairId($orderData['repair_site_id']);
        if (!$oid) {
            json_output('', '生成维修单号失败,error:'.$repair_point.'无法生成单号', false);
        }
        $orderData['maintain_id'] = $oid;
        $orderData['status_id'] = 1; //订单状态,默认是1
        $orderData['source_int_id'] = $orders['reference_order_number']; //来源单号
        if (!$orderData['source_int_id']) {
            json_output('', '来源单号不能为空', false);
        }
        $orderData['consumer_name'] = $orders['customer_name']?$orders['customer_name']:$this->getData['user']; //客户名称
        $orderData['consumer_phone'] = $orders['customer_phone']?$orders['customer_phone']:'0755-23508000'; //客户电话
        $orderData['consumer_email'] = $orders['customer_email']?$orders['customer_email']:'marketing@4px.com'; //客户邮箱
        $orderData['consumer_address'] = $orders['customer_address']?$orders['customer_address']:'深圳市宝安区西乡宝源路财富港大厦D座25楼'; //客户地址
        $orderData['door_to_door_pickup'] = $orders['pick_up_service'] == 'N' ? '0' : 1; //上门取件 0否 1是
        $orderData['fault_description'] = $orders['comment'];
        if($orders['price_type']=='A'){
            $orderData['price_type'] = '0';
        }elseif($orders['price_type']=='B'){
            $orderData['price_type'] = '1';
        }
        $orderData['add_user'] = $this->getData['user']; //添加人
        $orderData['add_time'] = date('Y-m-d H:i:s'); //添加时间
        $orderData['maintain_type_id'] = 9; //第四方维修类型
        $this->order_model->addOrSetOrder($orderData);

        //添加产品
        $productList = $orders['products_list'];
        if(!$productList || !is_array($productList)){
            json_output('', '产品为空或不是数组', false);
        }
        $productInfo['maintain_id'] = $oid;
        foreach ($productList as $rs) {
            if(!$rs || !is_array($rs))continue;
            $productInfo['sort_id'] = $rs['products_sort']?$rs['products_sort']:1;
            $productInfo['brand_id'] = $rs['products_brand_id'];
            $productInfo['brand_name'] = $rs['products_brand_name'];
            $productInfo['product_model'] = $rs['products_model'];
            $productInfo['source_product_id'] = $rs['products_id'];
            $productInfo['imei'] = $rs['imei'];
            $productInfo['size'] = $rs['size'];
            $productInfo['color'] = $rs['color'];
            $productInfo['is_bluetooth'] = $rs['is_bluetooth'];
            $productInfo['is_yaokong'] = $rs['is_remote_control'];
            $this->product_model->addOrSetProduct($productInfo);
        }
        json_output('', '创建成功', true);

    }


    /***
     * 接受报价单数据
     */
    function get_priceList()
    {
        $orders = json_decode($this->getData['order'], true);
        $productList = $orders['products_list'];
        $oid = $orders['maintain_order_id'];
        if (!$oid or !$productList) {
            json_output('', '订单数据或产品数据为空', false);
        }
        foreach ($productList as $rs) {
            $is_accept_price = $rs['accepted'] == 'Yes' ? 1 : 0;
            $setData = array('is_accept_price' => $is_accept_price);
            $where = array('source_product_id' => $rs['products_id'], 'oid' => $oid);
            $this->common_model->update('maintain_product_price', $setData, $where);
        }
        json_output('', '接受数据成功!', true);

    }

    /**
     * 是否同意报价
     *
     */
    //function is_acc

    /**
     * 创建批量单的模块
     */
    public function CreateMultiOrder($orders)
    {

        $logInfo = array('file_path' => __FILE__ , 'fun' => __FUNCTION__ , 'data' => $orders);
        log_output($logInfo);
        $products = $orders['products_list'];
        if (!$orders) {
            json_output('' , 'Create order data can not be empty!' , false);
        }
        if (!$products || !is_array($products)) {
            json_output('' , 'Create product data can not be empty!' , false);
        }
        $point = strtolower($orders['repair_point']);
        $serviceCenter = $this->common_model->selectFirst('mt_service_center' , array('point' => $point));
        if (!$point) {
            json_output('' , '(repair site)service Center not exist' , false);
        }

        $orderNum = build_order_no("BO");
        $logInfo = array('file_path' => __FILE__ , 'fun' => __FUNCTION__ , 'data' => '451:' . $orderNum);
        log_output($logInfo);
        $orderData['order_num'] = $orderNum;
        $orderData['website_origin'] = $orders['website_origin'];
        $orderData['service_center'] = $serviceCenter['id'];
        $orderData['point'] = $serviceCenter['point'];
        $orderData['currency_code'] = $serviceCenter['currency'];
        $sourceSiteAry = array('ES' => 2 , 'RU' => 3 , 'DE' => 4 , 'GB' => 6 , 'US' => 7 , 'SZ' => 5);
        $sitePoint = strtoupper($point);
        //$orderData['source_site'] = $sourceSiteAry[$sitePoint]; //订单来源
        $orderData['service_type'] = $orders['repair_type'];
        $orderData['quantity'] = $orders['quantity'] ?: count($products);//预计数量
        $orderData['source_oid'] = $orders['reference_order_number'] ? $orders['reference_order_number'] : uniqid('OM');

        $orderData['consumer_name'] = $orders['customer_name'];
        $orderData['consumer_phone'] = $orders['customer_phone'];
        $orderData['consumer_email'] = $orders['customer_email'];
        //#卖家
        $merchantNum = (int) $orders['merchant_num'];
        if ($orders['merchant_num'] && $merchantNum != 35) {
            $merchantFirst = $this->common_model->selectFirst('mt_customers' , array('id' => $merchantNum));
            if ($merchantFirst['type'] != 1) {
                json_output($merchantFirst , 'No platform customers' , false);
            }
        }
        $orderData['merchant_num'] = $merchantNum;

        //#个人
        $consumerNum = 0;
        if (!$orderData['merchant_num'] && $orderData['consumer_email']) {
            $consumerFirst = $this->common_model->selectFirst('mt_customers' , array('email' => $orderData['consumer_email']));
            if ($consumerFirst['type'] == 3) {
                $consumerNum = $consumerFirst['id'];
            }
            else {
                $consumerData = array('name' => $orderData['consumer_name'] , 'email' => $orderData['consumer_email'] , 'tel' => $orderData['consumer_phone'] , 'type' => 3 , 'CurrencyIsoCode' => $serviceCenter['currency_code']);
                $consumerNum = $this->common_model->insert('mt_customers' , $consumerData);
            }
        }
        $orderData['add_user'] = $this->getData['user']; //添加人	
        $orderData['add_time'] = time(); //添加时间
        //地址相关 begin
        $orderData['delivery_country'] = $orders['delivery_country'];
        $orderData['delivery_city'] = $orders['delivery_city'];
        $orderData['delivery_state'] = $orders['delivery_state'];
        $orderData['delivery_street_address'] = $orders['delivery_street_address'];
        $orderData['delivery_zipcode'] = $orders['delivery_zipcode'];
        //地址相关 end


        $oid = $this->common_model->insert('mt_multi_orders' , $orderData);

        if (!$oid) {
            json_output($orderData , 'Failed to create the order' , false);
        }
        //验证产品类型是否存在
        foreach ($products as &$rs) {
            $productTypes = $this->common_model->selectFirst('mt_product_category' , array('sap_id' => $rs['category']));
            if (!$productTypes) {
                json_output($orderData , 'productType id:' . $rs['category'] . ' is not exist' , false);
            }
            $rs['category'] = $productTypes['id'];
        }
        unset($rs);
        $pids = array();
        //循环插入产品
        foreach ($products as $rs) {
            //add product
            $productData = array();
            $productData['oid'] = $oid;
            $productData['order_num'] = $orderNum;
            $productData['category_id'] = $rs['category'];
            $productData['waybill_num'] = '';
            //产品数量
            $quantity = $rs['product_quantity'] ? $rs['product_quantity'] : 1;
            for ($i = 0 ; $i < $quantity ; $i++) {
                $productData['sku'] = $rs['productSku'];

                $productData['attributes'] = $rs['attributes'];
                $productData['source_id_order'] = $rs['source_id_order'];
                $productData['brandCustomerNum'] = $rs['brandCustomerNum'];
                $productData['product_brand'] = $rs['product_brand'];
                $productData['product_model'] = $rs['product_model'];
                $productData['model_id'] = $rs['model_id'];
                $productData['customerRemark'] = $rs['remark_customer'];
                $productData['defectDes'] = $rs['defectDes'];
                $productData['imei'] = $rs['imei'];
                $productData['add_time'] = time();
                $productData['add_user'] = 'system';
                $pids[] = $this->common_model->insert('mt_multi_products' , $productData);
            }
        }
        json_output(array('oid' => $orderNum , 'orderid' => $oid , 'pids' => $pids,) , 'Create order successfully' , true);
    }
}
